package com.web.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.web.utils.FileUtil;
@Controller
@RequestMapping("basefile")
public class BaseFileController {
    @Value(value = "/basefile/pubImgage/")
    private String uploadPath;
    @Value(value = "/basefile/download/")
    private String downloadUrl;
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, String fileName) {
        // BaseFile bf=bfs.getSingleByHql(" and fileName='"+fileName+"'");
        String filePath = uploadPath + fileName;
        System.out.println("filePath:" + filePath);
        try {
            return FileUtil.download(request, filePath);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    
    @ResponseBody
    @RequestMapping("/uploadImage")
    public Map<String, Object> uploadNew(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (file.isEmpty()) {
            resultMap.put("success", 0);
            resultMap.put("message", "获取文件失败，请重新上传！");
            return resultMap;
        }
        SimpleDateFormat smp = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String homeDir = System.getProperties().getProperty("user.home");
        String filePath = uploadPath;
        String desFileName = smp.format(new Date()) + "."
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        boolean b = FileUtil.Save(homeDir + filePath, file, desFileName);
        if (b) {
            resultMap.put("uploaded", 1);
            resultMap.put("fileName", desFileName);
            resultMap.put("url", ".." + downloadUrl + "?fileName=" + desFileName);
        } else {
            resultMap.put("uploaded", 0);
            resultMap.put("url", ".." + downloadUrl + "?fileName=default.jpg");
            resultMap.put("fileName", desFileName);
        }
        return resultMap;
    }
}